<?php

namespace app\system\service;

use think\facade\Db;

class RoleMenuService
{
    public function saveRoleMenu($request)
    {
        //开启事务
        Db::startTrans();
        try {

            $saveData = $request->post('menuIds');

            $roleId = $request->post('roleId');

            Db::name('role_menu')
                ->where('roleId', $roleId)
                ->delete();

            foreach ($saveData as $menuId) {
                $data = ['roleId' => $roleId, 'menuId' => $menuId];
                $where = [];
                $where['roleId'] = ['roleId', '=', "{$roleId}"];
                $where['menuId'] = ['menuId', '=', "{$menuId}"];
                //查询是否存在
                $roleMenuList = Db::table('role_menu')->where($where)->findOrEmpty();
                if (empty($roleMenuList)) {
                    $data['createdAt'] = date("Y-m-d H:i:s");
                    //插入
                    Db::name('role_menu')->insert($data);
                } else {
                    $data['updatedAt'] = date("Y-m-d H:i:s");
                    //更新
                    Db::name('role_menu')->update($data);
                }
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return (['success' => false, 'info' => $e->getMessage()]);
        }
        return (['success' => true, 'info' => '保存成功!']);
    }

    public function getRoleMenuIdsById($request)
    {

        try {
            $id = $request->post('id');
            //分页
            $menuList = Db::name('role_menu')
                ->where('roleId', $id)->column('menuId');

            return (['success' => true, 'info' => '', 'data' => $menuList]);
        } catch (\Exception $e) {
            return (['success' => false, 'info' => $e->getMessage()]);
        }
    }
}